import { getFootballLiveList } from '@/server/news'
import { useRequest, useSafeState, useUpdateEffect } from 'ahooks'
import { useEffect, } from 'react'
import { getStartEndTime } from '@/common/tool'
import dayjs from 'dayjs'
import styles from './styles.module.scss'
import RenderJudge from "@/components/RenderJudge"
import Link from 'next/link'
import { week } from '@/common/tool'
import { NavList } from '@/common/enum'
import { getBasketballLiveList } from '@/server/news'
import Image from '@/components/Image'
import { cloneDeep } from 'lodash'
import { IndexBar } from 'antd-mobile/2x'

const Live = ({ liveListData, match, ready, style, container, initFetch }) => {
  const useInitEffect = initFetch ? useEffect : useUpdateEffect //每次初始化都更新，只在数据更新时初始化
  const [hotScore, setHotScore] = useSafeState(0) //0 全部 1 热门
  const [data, setData] = useSafeState(() => {
    const state = []
    if (typeof liveListData?.today !== 'undefined') {
      state.push({ time: liveListData?.today?.time, data: liveListData?.today?.data })
    }
    if (typeof liveListData?.yesterday !== 'undefined') {
      state.push({ time: liveListData?.yesterday?.time, data: liveListData?.yesterday?.data })
    }
    return state
  })

  useEffect(() => {
    const data = [
      { time: liveListData?.today?.time, data: liveListData?.today?.data },
      { time: liveListData?.yesterday?.time, data: liveListData?.yesterday?.data }
    ]
    setData(data)
  }, [liveListData])
  const api = {
    "0": getFootballLiveList,
    '1': getFootballLiveList,
    '2': getBasketballLiveList,
  }

  // const containerRef = useRef(null);
  // const wrapperRef = useRef(null);

  const { runAsync } = useRequest(Reflect.get(api, match.type), {
    onSuccess: (res, [params]) => {
      if (params?.count === 1) {
        //当前的
        setData([{ time: getStartEndTime().todayStartTime, data: res }])
      }
      if (params?.count === 2) {
        setData(s => [...s, { time: getStartEndTime().tomorrowEndTime, data: res }])
      }
    },
    manual: true,
    ready,
  })

  useUpdateEffect(() => {
    if (hotScore === 1) {
      let state = cloneDeep(data)
      const info = state?.reduce((sum, currentValue) => {
        const hotMatch = currentValue?.data?.filter(r => r?.isHot === 1) || []
        return [...sum, { time: currentValue?.time, data: hotMatch }]
      }, [])
      setData(info)
      return
    }
    if (hotScore === 0) {
      window.location.reload()
    }
  }, [hotScore])


  // const [list, scrollTo] = useVirtualList(data, {
  //   containerTarget: containerRef,
  //   wrapperTarget: wrapperRef,
  //   itemHeight: (i, data) => data?.time ? remToPx(50) : remToPx(180),
  //   overscan: 5,
  // });

  useInitEffect(() => {
    (async () => {
      const startParams = {
        pageNum: 1,
        pageSize: 3000,
        type: 1,
        date: getStartEndTime().todayStartTime
      }
      const endParams = {
        pageNum: 1,
        pageSize: 3000,
        type: 1,
        date: getStartEndTime().tomorrowEndTime
      }
      if (Number(match?.type === 0)) {
        if (!ready) return
        const [todayLiveData, yesterdayLiveData, todayLiveDataBasketball, yesterdayLiveDataBasketball] = await Promise.all([getFootballLiveList(startParams), getFootballLiveList(endParams), getBasketballLiveList(startParams), getBasketballLiveList(endParams)])
        //全部
        const currentDay = [...todayLiveData?.map(row => ({ ...row, matchType: 1 })), ...todayLiveDataBasketball?.map(row => ({ ...row, matchType: 2 }))] //今天的数据

        const yesterday = [...yesterdayLiveData?.map(row => ({ ...row, matchType: 1 })), ...yesterdayLiveDataBasketball?.map(row => ({ ...row, matchType: 2 }))] //明天
        const state = {
          today: {
            time: getStartEndTime().todayStartTime,
            data: currentDay
          },
          yesterday: {
            time: getStartEndTime().tomorrowEndTime,
            data: yesterday
          }
        }
        const cdate = [{ time: state?.today?.time, data: state?.today?.data }, { time: state?.yesterday?.time, data: state?.yesterday?.data }]
        setData(cdate)
        return
      }


      const params = {
        pageNum: 1,
        pageSize: 1000,
        type: 1,
        date: getStartEndTime()?.todayStartTime,
        count: 1,
      }
      if (match?.id) params.eventIds = match?.id
      await runAsync(params)
      params.date = getStartEndTime().tomorrowEndTime
      params.count = 2
      await runAsync(params)
    })()
  }, [match])
  const result = (row) => {
    if (!row?.matchType && row.status >= 2 && row.status <= 7) return true //没有这个字段，足球没有
    if (String(row?.matchType) === "1" && row.status >= 2 && row.status <= 7) return true
    if (String(row?.matchType) === "2" && row.status >= 2 && row.status <= 9) return true
    return false
  }
  const link = (row) => {
    const d = [NavList.a, ...NavList.f, ...NavList.b]
    const typer = row?.matchType || match?.type
    const { eventId } = row
    if (row?.liveUrlList?.length > 0) {
      const has = d.some(v => v.id === Number(eventId))
      if (has) return `/live/${typer}/${row?.id}/${eventId}`
      return `/live/${typer}/${row?.id}`
    }
    return "https://www.xinqiuzhibo.com/"
  }


  const scoreData = (row) => {
    if (!result(row)) return ['', '']
    //比分 
    if (row?.matchType === 1 || !row?.matchType) {
      //足球直接去字段比分
      return [row?.homeTeamScore, row?.awayTeamScore]
    }
    if (row?.matchType === 2) {
      const s1 = row?.homeTeamScore?.reduce((sum, current) => sum += current, 0)
      const s2 = row?.awayTeamScore?.reduce((sum, current) => sum += current, 0)
      return [s1, s2]
    }
    return ['', '']
  }
  return (
    <>
      <aside className={styles.h5LiveTab}>
        <p>直播表</p>
        <div>
          <span onClick={() => setHotScore(0)} className={hotScore === 0 ? styles.hotScore : null}>全部</span>
          <span onClick={() => setHotScore(1)} className={hotScore === 1 ? styles.hotScore : null}>热门</span>
        </div>
      </aside>
      <section style={style} className={styles.h5LiveList}>
        <section style={{ ...container }} className={styles.h5scrollBox}>
          <IndexBar sticky>
            {
              data?.map((item, index) => (
                <IndexBar.Panel
                  index={dayjs(item?.time).format('M月D日') + week[dayjs(item?.time).format('d')]}
                  title={dayjs(item?.time).format('M月D日') + week[dayjs(item?.time).format('d')]}
                  key={index}
                  brief={
                    <span>
                      {week[dayjs(item?.time).format('d')]}
                    </span>
                  }
                >
                  {
                    item?.data?.map((row) => (
                      <>
                        <RenderJudge value={row?.id} active={
                          <li className={styles.h5liveli}>
                            <div>
                              <span>{dayjs(row?.matchTime * 1000).format('HH:mm')}</span>
                              <div>
                                <em>{row?.eventName}</em>
                                <span className={styles.matchInfo}>
                                  <RenderJudge value={Number(row?.matchType || match?.type) === 1} active={
                                    <>
                                      <span className='textoverone'>{row?.homeTeamName}</span>
                                      <Image className={styles.left} src={row?.homeTeamLogo} type={row?.matchType || match?.type}></Image>
                                      <RenderJudge value={result(row)} active={
                                        <>
                                          <em className={styles.scoreLeft}>{scoreData(row)[0]}</em>
                                          <em>-</em>
                                          <em className={styles.scoreRight}>{scoreData(row)[1]}</em>
                                        </>
                                      } inactive={
                                        <i>VS</i>
                                      } />
                                      <Image className={styles.right} src={row?.awayTeamLogo} type={row?.matchType || match?.type}></Image>
                                      <span className='textoverone'>{row?.awayTeamName}</span>
                                    </>
                                  } inactive={
                                    <>
                                      <span className='textoverone'>{row?.awayTeamName}</span>
                                      <Image className={styles.left} src={row?.awayTeamLogo} type={row?.matchType || match?.type}></Image>
                                      <RenderJudge value={result(row)} active={
                                        <>
                                          <em className={styles.scoreLeft}>{scoreData(row)[1]}</em>
                                          <em>-</em>
                                          <em className={styles.scoreRight}>{scoreData(row)[0]}</em>
                                        </>
                                      } inactive={
                                        <i>VS</i>
                                      } />
                                      <Image className={styles.right} src={row?.homeTeamLogo} type={row?.matchType || match?.type}></Image>
                                      <span className='textoverone'>{row?.homeTeamName}</span>
                                    </>
                                  } />
                                </span>
                                <RenderJudge value={result(row)} active={
                                  <Link href={link(row)}>
                                    <a className={styles.watch}>直播中</a>
                                  </Link>
                                } />
                                <RenderJudge value={row?.status === 1} active={
                                  <span className={styles.noStart}>
                                    未开始
                                  </span>
                                } />
                              </div>
                              <span>
                                <Link href={process.env.NEXT_PUBLIC_XQWEB}>
                                  <em>比分</em>
                                </Link>
                                <Link href={process.env.NEXT_PUBLIC_XQWEB}>
                                  <em>福利</em>
                                </Link>
                              </span>
                            </div>
                          </li>
                        } inactive={
                          <li className={styles.h5time}>
                            {dayjs(row?.time).format('M月D日') + week[dayjs(row?.time).format('d')]}
                          </li>
                        } />
                      </>
                    ))
                  }
                </IndexBar.Panel>
              ))
            }
          </IndexBar>
        </section>

      </section>
    </>
  )
}

Live.defaultProps = {
  ready: false,
  container: {
    height: '14.36rem',
  },
  wrapper: {},
  initFetch: false
}

export default Live